<template>
  <el-dialog style="width: 70vw;" :title="form.id ? '编辑' : '新增'" v-model="visible"
             :close-on-click-modal="false" draggable>


    <el-row v-show="showSearch">
      <el-form :model="state.queryForm" ref="queryRef" :inline="true" @keyup.enter="getDataList">
        <el-form-item label="设备名称" prop="deviceName" >
          <el-input placeholder="请输入设备名称" v-model="state.queryForm.deviceName" />
        </el-form-item>
        <el-form-item label="设备编号" prop="deviceCode" >
          <el-input placeholder="请输入设备编号" v-model="state.queryForm.deviceCode" />
        </el-form-item>
        <el-form-item label="设备在线状态" prop="deviceOnlineStatus">
          <el-select v-model="state.queryForm.deviceOnlineStatus" placeholder="请选择设备在线状态">
            <el-option :key="index" :label="item.label" :value="item.value" v-for="(item, index) in iot_device_online_status_dict"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设备所在地址" prop="deviceAddress" >
          <el-input placeholder="请输入设备所在地址" v-model="state.queryForm.deviceAddress" />
        </el-form-item>
        <el-form-item label="设备分类" prop="deviceCategoryId">
          <el-select v-model="state.queryForm.deviceCategoryId" placeholder="请选择设备分类">
            <el-option :key="index" :label="item.categoryName" :value="item.id" v-for="(item, index) in thisPageState.deviceCategoryList"></el-option>

          </el-select>
        </el-form-item>
        <el-form-item label="设备绑定状态" prop="deviceBindStatus">
          <el-select v-model="state.queryForm.deviceBindStatus" placeholder="请选择绑定状态">
            <el-option :key="index" :label="item.label" :value="item.value" v-for="(item, index) in iot_device_bind_status_dict"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button icon="search" type="primary" @click="getDataList">
            查询
          </el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-row>
    <el-row>
      <div class="mb8" style="width: 100%">
        <right-toolbar v-model:showSearch="showSearch"
                       class="ml10 mr20" style="float: right;"
                       @queryTable="getDataList"></right-toolbar>
      </div>
    </el-row>
    <el-table :data="state.dataList" v-loading="state.loading" border
              :cell-style="tableStyle.cellStyle" :header-cell-style="tableStyle.headerCellStyle"
              @selection-change="selectionChangHandle"
              @sort-change="sortChangeHandle">
      <el-table-column type="selection" width="40" align="center" />
      <el-table-column type="index" label="#" width="40" />
      <el-table-column prop="deviceName" label="设备名称"  show-overflow-tooltip/>
      <el-table-column prop="deviceCode" label="设备编号"  show-overflow-tooltip/>
      <el-table-column prop="deviceImg" label="设备图片路径"  show-overflow-tooltip/>
      <el-table-column prop="deviceOnlineStatus" label="设备在线状态"  show-overflow-tooltip>
        <template #default="scope">
          <dict-tag :options="iot_device_online_status_dict" :value="scope.row.deviceOnlineStatus"></dict-tag>
        </template>
      </el-table-column>
      <el-table-column prop="deviceAddress" label="设备所在地址"  show-overflow-tooltip/>
      <el-table-column prop="deviceCategoryId" label="设备所属设备分类ID"  show-overflow-tooltip/>
      <el-table-column prop="deviceBindStatus" label="绑定状态"  show-overflow-tooltip>
        <template #default="scope">
          <dict-tag :options="iot_device_bind_status_dict" :value="scope.row.deviceBindStatus"></dict-tag>
        </template>
      </el-table-column>
      <el-table-column prop="deviceRemark" label="设备信息备注"  show-overflow-tooltip/>
      <el-table-column prop="deviceExtraJsonFields" label="设备额外字段"  show-overflow-tooltip/>
      <el-table-column prop="createBy" label="创建者"  show-overflow-tooltip/>
      <el-table-column prop="createTime" label="创建时间"  show-overflow-tooltip/>
      <el-table-column prop="updateTime" label="更新时间"  show-overflow-tooltip/>

    </el-table>
    <pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" v-bind="state.pagination" />
    <template #footer>
        <span class="dialog-footer">
          <el-button @click="visible = false">取消</el-button>
          <el-button type="primary" @click="onSubmit(selectObjs)" :disabled="(loading || multiple)">确认</el-button>
        </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="DuorouGreenhouseDeviceDialog">
import {useDict} from '/@/hooks/dict';
import {useMessage} from "/@/hooks/message";
import {getObj, addObj, putObj} from '/@/api/duorou/duorouGreenhouseDevice'
import {rule} from '/@/utils/validate';
import { BasicTableProps, useTable } from "/@/hooks/table";
import { fetchList,delObjs } from "/@/api/iot/iotDevice";

import { fetchList as fetchDeviceCategoryList } from "/@/api/iot/iotDeviceCategory";



/**
 * 定义组件属性 接收传递来的 大棚ID
 */
const props = defineProps([
    'greenHouseID'
])


const emit = defineEmits(['refresh']);

const visible = ref(false)
const loading = ref(false)
// 定义字典

// 提交表单数据
const form = reactive({
  id: '',
  greenhouseId: '',
  deviceId: '',
  formList:[]
});



// 打开弹窗
const openDialog = (id: string) => {
  visible.value = true
  form.id = ''
//  重置数据
  resetQuery()
};

// 提交
const onSubmit = async (greenhouseDeviceList:[]) => {
  const valid =true;
  if (!valid) return false;
  form.formList=greenhouseDeviceList
  try {
    loading.value = true;
    await addObj(form.formList);
    useMessage().success(form.id ? '修改成功' : '添加成功');
    visible.value = false;
    emit('refresh');
  } catch (err: any) {
    useMessage().error(err.msg);
  } finally {
    loading.value = false;
  }
};

// 暴露变量
defineExpose({
  openDialog
});


/**
 * 获取所有未绑定的设备
 */


// 搜索变量
const queryRef = ref()
const showSearch = ref(true)
// 多选变量
const selectObjs = ref([]) as any
const multiple = ref(true)


/**
 * 获取所有未绑定的设备
 */
const state: BasicTableProps = reactive<BasicTableProps>({
  queryForm: {
    deviceBindStatus:'0' //0未绑定 1 已绑定
  },
  pageList: fetchList
})

//  table hook
const {
  getDataList,
  currentChangeHandle,
  sizeChangeHandle,
  sortChangeHandle,
  tableStyle
} = useTable(state)

// 清空搜索条件
const resetQuery = () => {
  // 清空搜索条件
  queryRef.value?.resetFields()
  // 清空多选
  selectObjs.value = []
  getDataList()
}


// 多选事件,
const selectionChangHandle = (objs: { id: string }[]) => {
  selectObjs.value = objs.map(({ id }) => {
    return {
      deviceId:id,
      greenhouseId:props.greenHouseID
    }
  });
  multiple.value = !objs.length;
};


/**
 * 去除模板中直接使用的statu自定义一个自己需要使用的 页面state
 */
const thisPageState=reactive({
  deviceCategoryList:[],//所有设备分类

})



/**
 * 获取所有设备分类信息
 *
 */

function getDeviceCategoryList(){
  fetchDeviceCategoryList().then(res=>{
    console.log(res)
    thisPageState.deviceCategoryList=res.data.records;
  })
}
getDeviceCategoryList()



/**
 * 获取在线状态和绑定状态的字典
 */
const { iot_device_online_status_dict, iot_device_bind_status_dict } = useDict('iot_device_online_status_dict', 'iot_device_bind_status_dict');


</script>